package com.ruoyi.central.publisher.subscription.process.step.event;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.central.domain.TopCentralProcessStep;
import com.ruoyi.central.domain.TopCentralProcessStepRun;
import com.ruoyi.central.publisher.event.ProcessStepEvent;
import com.ruoyi.central.service.ITopCentralProcessStepRunService;
import com.ruoyi.common.enums.common.State;
import com.ruoyi.common.exception.base.service.ServiceException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Classname ProcessStepEventSubscription
 * @Author: sunluquan
 * @Date: 2022/5/19 11:36
 * @Description TODO
 * 工序 对象事件订阅
 */
@Component
@Order(1)
public class ProcessStepEventSubscription {

    @Autowired
    private ITopCentralProcessStepRunService processStepRunService;

    /**
     * 工序修改事件订阅
     * @param event
     */
    @EventListener(value = ProcessStepEvent.class,condition = "#event.getSignEnum().name() == 'UPDATE'")
    public void updateEvent(ProcessStepEvent event){

        if(getArtProcessRunBindingCount(event, processStep -> State.DISABLE == processStep.getState() ) >0 ){
            throw new ServiceException("有正在使用中的工序，不能修改数据状态为：{}，请先删除 工序执行数据 ！", State.DISABLE.getInfo());
        }

    }

    /**
     * 获取 当前工序集合 绑定的 工序执行数量
     * @param event
     * @param predicate
     * @return
     */
    private long getArtProcessRunBindingCount(ProcessStepEvent event,Predicate<? super TopCentralProcessStep> predicate){

        Collection<TopCentralProcessStep> processSteps = event.getSources();

        List<Integer> processStepIds = CollectionUtils.mapToList(processSteps, TopCentralProcessStep::getId, predicate);

        if(StringUtils.isNotEmpty(processStepIds)){

            LambdaQueryWrapper<TopCentralProcessStepRun> queryWrapper = processStepRunService.lambdaQuery();

            if(processStepIds.size()==1){
                queryWrapper.eq(TopCentralProcessStepRun::getId,CollectionUtils.getFirst(processStepIds));
            }else{
                queryWrapper.in(TopCentralProcessStepRun::getId,processStepIds);
            }

            return processStepRunService.count(queryWrapper);
        }

        return 0L;
    }

    /**
     * 工序删除事件订阅 只订阅操作类型为手动的
     * @param event
     */
    @EventListener(value = ProcessStepEvent.class,condition = "#event.getSignEnum().name() == 'DELETE' and !#event.isOperationType() ")
    public void deleteEvent(ProcessStepEvent event){

        if(getArtProcessRunBindingCount(event,null) >0 ){
            throw new ServiceException("有正在使用中的工序，不能进行删除，请先删除 工序执行数据 ！");
        }

    }
}
